// px 字符串的正则匹配
const pxRegegExp = /\b(\d+(\.\d+)?)px\b/gi

const px2calc = (opts = {}) => {
  let _opts = Object.assign({
    max: '2560px', // 最大分辨率
    min: '320px', // 最小分辨率
    preferences: '100vw', // clamp 函数首选参数默认 100vw
    idealWidth: '1920' // 理想宽度，不需要单位
  }, opts)
  // opt 为构建的参数
  return function (root) {
    root.walkRules(function (rule) {
      rule.walkDecls(function (decl) {
        try {
          let declVal = decl.value.replaceAll(pxRegegExp, (match) => {
            let pxVal = match.substring(0, match.length - 2)
            return `calc(${pxVal} * (clamp(${_opts.min}, ${_opts.preferences}, ${_opts.max}) / ${_opts.idealWidth}))`
          })
          decl.value = declVal
        } catch (e) {
          console.log('插件报错了 ==》')
          console.log(e)
        }
      })
    })
  }
}


module.exports = px2calc

